<template>
	<view class="rectificationContent">
		<commonNavBar title="智能客服"  ></commonNavBar>   
		<scroll-view id="chartList" class="centre" :scroll-y="true" :scroll-top="scrollTop" :scroll-with-animation="true" :style="{height: chartHeight + 'px' ,width:'715rpx' }">
			<image id="chart1" src="/static/img/robot.png" class="robot"></image>
			<view id="chart2" class="initial">👋{{ user }}，您好，我是智能客服小智，请问有什么可以帮您？</view> 
			<view class="robotList">
				<view :id="'chart'+(index+2)"  class="li" v-for="(item,index) in robotList">
					<!-- 右侧内容 -->
					<view class="double" v-if="!item.leftStatus" >
						<image class="message-icon message-icon-loading" src="/static/img/message-loading.png" v-if=" item.loading" ></image>
						<image class="message-icon"  src="/static/img/message-error.png" @tap="reSend(item.problemResult,index)" v-if=" item.error" ></image>
						<button>{{ item.problemResult }} </button> 
					</view>
					<!-- 左侧内容 -->
					<view class="robotMessage" :key="item.id" v-if="item.leftStatus &&  item.type == 'text'"  > 
						<image src="/static/img/robot.png" mode=""></image>
						<view class="doublec">
							<view class="left-message" v-html="item.problemResult"> </view>
						</view>
					</view>
					<view class="robotMessage" :key="item.id"  v-if="item.leftStatus &&  item.type == 'select'"> 
						<image src="/static/img/robot.png" mode=""></image>
						<view class="doublec">
							<uni-list-item v-for="(m , i) in item.list" :showArrow="true" :title="m.problemAbstract" :clickable="false" :ellipsis="1" link="navigateTo"
								 @tap="showInfo(m.problemResult,m.problemAbstract)"  :customStyle="{padding:'0px',titleFontSize:'18rpx',titleFontColor:'#787878'}"
							/>
							<view class="load-more" v-if="item.list.length >= messageSize" @tap="loadMore(index)">点击查看更多</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="fixed">
			<image @click="toggleMode" :src="mode === 'voice' ? voiceImgPath : textImgPath"></image>
			<view class="input-container">
				<uni-easyinput 
					v-show="mode === 'text'" type="text" class="text"
					v-model="inputValue" 
					:clearable="false"
					placeholder="请输入您想要咨询的问题">
				</uni-easyinput>
			</view>
			<view v-show="mode === 'voice'" @longpress="startRecording" @touchend="stopRecording" class="voice">
			  <text>{{ recording ? '松开结束' : '按住说话' }}</text>
			</view>
			<!-- <image src="/static/img/add.png" class="add"></image> -->
			<view class="send" @click="send(true)">发送</view>
		</view>
	</view>
</template>

<script>
	import commonNavBar from '@/components/CommonNavBar.vue';
	
	export default {
		components:{
			commonNavBar
		},
		data() {
			return { 
				user: '王宇',
				scrollTop:1,
				old: {
					scrollTop: 0
				},
				chartHeight: 1,
				pageTopHeight : 0,
				messageIndex: 0, 
				messageSize: 5, 
				intelligentOptionsData: {
					list: [{
						listId: 0,
						title: '如何查询企业证件'
					},
					{
						listId: 1,
						title: '企业违法经营，应该怎么处理'
					},
					{
						listId: 2,
						title: '违规使用添加剂该如何处理'
					},
					{
						listId: 3,
						title: '企业证照过期该如何处理'
					},
					{
						listId: 4,
						title: '从业人员健康证过期如何处理'
					}],
					piece: [{
						pieceId: 0,
						title: '工艺解析'
					},
					{
						pieceId: 1,
						title: '历史执法文书'
					},
					{
						pieceId: 2,
						title: '企业风险浏览'
					},
					{
						pieceId: 3,
						title: '法律依据'
					},
					{
						pieceId: 4,
						title: '中外案例查询'
					},
					{
						pieceId: 5,
						title: '最新领导指示'
					}]
				},
				activeIndex: -1,
				mode: 'text', // 当前模式：'voice' 为语音模式，'text' 为文本模式
				recording: false, // 是否正在录音
				voiceImgPath: '/static/img/voice.png', // 语音模式下的图片路径
				textImgPath: '/static/img/text.png', // 文本模式下的图片路径
				inputValue: '',
				robotList: []
			}
		}, 
		onLoad(options) {
			
		},
		onReady() {
			//this.chartHeight = uni.getSystemInfoSync().
			const query = uni.createSelectorQuery().in(this);
			const that = this;
			query.select('#chartList').boundingClientRect(data => {
			 that.chartHeight = uni.getSystemInfoSync().screenHeight - data.top - data.bottom 
			 that.pageTopHeight = data.top;
			}).exec(); 
			//获取存储的消息列表
			const robotJsonArray = uni.getStorageSync("rebot"); 
			let messageList = [];
			if(robotJsonArray != null){ 
				for (var i = 0; i < robotJsonArray.length; i++) { 
					if(this.getHoursBetweenTimestamps(Date.now(),robotJsonArray[i].time) <= 24){
						messageList.push(robotJsonArray[i]);
					} 
				}
				this.robotList = messageList;
				uni.setStorageSync("rebot",this.robotList);
				this.messageIndex = messageList.length;
				this.toBottom(); 
			}
		}, 
		mounted() {
			this.user = uni.getStorageSync('userName')
		},
		methods: {
			goBack() {
				uni.navigateBack();
			},  
			toggleMode() {
				this.mode = this.mode === 'voice' ? 'text' : 'voice';
			},
			startRecording() {
				this.recording = true; 
			},
			stopRecording() {
				this.recording = false; 
			},
			reSend(message,index){
				this.inputValue = message;
				this.$set(this.robotList[index],'loading',true);
				this.$set(this.robotList[index],'error',false);
				this.send(false,index);
			},
			async send(addMessage,index) { 
				if(this.inputValue !== '') { 
					let  timeLong = Date.now();
					if(addMessage){
						//添加用户发送消息
						this.robotList.push({
							leftStatus: false,
							error: false,
							loading: false,
							time:timeLong,
							problemResult: this.inputValue,
							type: 'text' 
						})
					} 
					//默认最后一条消息的下表，用来修改消息的加载状态，错误状态
					this.messageIndex = this.robotList.length - 1; 
					if(index){
						//点击发送失败的消息前面叹号的时候使用点击的那个下标
						this.messageIndex = index;
					}
					//添加用户发送消息加载动画
					this.$set(this.robotList[this.messageIndex],'loading',true);
					//滚动到页面底部
					this.toBottom();
					try { 
						let data = {
							message: this.inputValue,
							pageNum: 0,
							pageSize: this.messageSize,
						}
						this.inputValue = '';
						const res = await uni.$api.sendMessage(data);
						if(res.data.code != '0'){
							this.$set(this.robotList[this.messageIndex],'loading',false);
							this.$set(this.robotList[this.messageIndex],'error',true); 
							return;
						}
						//添加消息返回信息到列表
						if(res.data.data == '') {
							this.robotList.push({
								leftStatus: true,
								error: false,
								loading: false,
								problemResult: '暂时无法解决您的问题',
								time:timeLong,
								type:'text'
							})
						}else {
							if(res.data.data != undefined && res.data.data.length == 1){
								this.robotList.push({
									leftStatus: true,
									problemResult: res.data.data[0].problemResult,
									time:timeLong,
									error: false,
									loading: false,
									type: 'text',
									id: res.data.data[0].id,
									problemTable: res.data.data[0].problemTable,
									returnContentName: res.data.data[0].returnContentName,
									returnTitleName: res.data.data[0].returnTitleName,
								})
							} else {
								this.robotList.push({
									leftStatus: true,
									error: false,
									loading: false, 
									time:timeLong,
									type: 'select', 
									list: res.data.data
								})
								
							}
						}
						//设置发送的消息加载状态
						this.$set(this.robotList[this.messageIndex],'loading',false);
					} catch (error) {
						//设置发送的消息加载状态
						this.$set(this.robotList[this.messageIndex],'loading',false);
						//消息发送失败，将消息状态改成失败
						this.$set(this.robotList[this.messageIndex],'error',true); 
						console.error(error)
					} 
					//滚动到页面底部
					this.toBottom();
					//存储数据到本地24小时
					uni.setStorageSync("rebot",this.robotList);
				}
			},
			toBottom(){
				const that = this;
				this.scrollTop = this.old.scrollTop;
				this.$nextTick(function(){
					const query = uni.createSelectorQuery().in(that); 
					query.select('.robotList').boundingClientRect(data => { 
					  that.scrollTop = data.height  ;
					  that.old.scrollTop = data.height  ;
					}).exec(); 
				})
			},
			showInfo(returnContentName,returnTitleName) {  
				uni.navigateTo({
					url:'/pages/robot/messageInfo',
					success: (res) => {
						res.eventChannel.emit('updatePageData',{ data:'', title: returnTitleName ,content: returnContentName })
					}
				})
			},
			loadMore(index){
				if(index - 1 >= 0){
					const content = this.robotList[index - 1].problemResult;
					uni.navigateTo({
						url:'/pages/robot/loadMoreList?content='+content 
					})
				}
			},
			getHoursBetweenTimestamps(timestamp1, timestamp2) {
			  const diff = Math.abs(timestamp1 - timestamp2);
			  const hours = Math.floor(diff / (1000 * 60 * 60));
			  return hours;
			}

		},
		watch: {
			
		},
	}
</script>

<style lang="scss">
	.rectificationContent {
		background: #F9F9F9;
		height: calc(100vh - 195rpx);

		.upper {
			position: fixed;
			z-index: 1;
			top: 0;
			left: 0;
			width: 100%;

			.title {
				background: url('../../static/img/inspectBg.png');
				background-size: cover;
				width: 100%;
				height: 115rpx;
				line-height: 115rpx;
				position: relative;
				display: flex;
				justify-content: center;

				.arrow {
					position: absolute;
					left: 33rpx;
					top: 50%;
					transform: translate(0%, -50%);
					width: 100rpx;
					height: 100rpx;
					 
					&::before {
						display: block;
						content: "";
						position: absolute;
						top: 50%;
						left: 0%;
						width: 20rpx;
						height: 20rpx;
						border-left: 1px solid #fff;
						border-top: 1px solid #fff;
						transform: translate(0%, -50%) rotate(-45deg);
					}
				}

				text {
					font-size: 30rpx;
					font-family: PingFangSC-Medium, PingFang SC;
					font-weight: 500;
					color: #FFFFFF;
					letter-spacing: 1px;
				}
			}
		}

		.centre {
			margin: 115rpx 0 0 0;
			padding: 10rpx 17.5rpx 0 17.5rpx;
			height: calc(100vh - 280rpx);
			overflow-x: hidden;
			display: flex;
			flex-direction: column;
			
			.robot {
				width: 75rpx;
				height: 64rpx;
			}
			
			.initial {
				width: 100%;
				height: 56rpx;
				line-height: 56rpx;
				background: #FFFFFF;
				box-shadow: 0rpx 0rpx 29rpx 0rpx rgba(0,0,0,0.05);
				border-radius: 15rpx;
				margin: 18rpx 0 12rpx 0;
				font-size: 18rpx;
				font-family: AppleColorEmoji;
				color: #333333;
				text-indent: 21rpx;
			}
			
			.ul {
				background: #FFFFFF;
				box-shadow: 0rpx 0rpx 29rpx 0rpx rgba(0,0,0,0.05);
				border-radius: 9rpx;
				padding: 0 21rpx;
				
				.li {
					height: 66rpx;
					line-height: 66rpx;
					border-bottom: 2rpx solid #E7E7E7;
					font-size: 18rpx;
					font-family: PingFangSC-Regular, PingFang SC;
					font-weight: 400;
					color: #333333;
					
					&:last-child {
						border-bottom: none;
					}
				}
			}
			
			.ol {
				display: flex;
				flex-direction: row;
				flex-wrap: wrap;
				margin: 28rpx auto 0;
				
				.li {
					padding: 0 46rpx;
					height: 56rpx;
					line-height: 56rpx;
					text-align: center;
					background: #FFFFFF;
					box-shadow: 0rpx 0rpx 29rpx 0rpx rgba(0,0,0,0.05);
					border-radius: 28rpx;
					font-size: 18rpx;
					font-family: PingFangSC-Regular, PingFang SC;
					font-weight: 400;
					color: #333333;
					margin: 0 0 28rpx 0;
					
					&+.li {
						margin: 0 0 0 13rpx;
					}
					
					&.active {
						background: #0552A9;
						color: #fff;
					}
				}
			}
			
			.robotList {
				
				.li {
					// height: 56rpx;
					// line-height: 56rpx;
					
					.double {
						width: 100%;
						display: flex;
						justify-content: flex-end;
						align-items: center;
						
						button {
							margin: 0;
							font-size: 18rpx;
							font-family: AppleColorEmoji;
							color: #333333;
							border-radius: 14rpx;
							background-color: #5074fa;
							color: #ffffff;
							border: 2rpx solid rgba(187, 187, 187, 0.5294117647);
							/* overflow: hidden; */
							padding: 0 20rpx;
							white-space: nowrap;
							text-overflow: ellipsis;
							line-height: 56rpx;
						}
					}
					
					.robotMessage {
						display: flex;
						align-items: flex-start;
						flex-direction: row;
						justify-content: flex-start;
						
						
						image {
							width: 59rpx;
							height: 50rpx;
							margin: 0 14rpx 0 0;
						}
						
						.doublec {
							margin: 0;
							font-size: 18rpx;
							font-family: AppleColorEmoji;
							color: #000;
							line-height: 56rpx;
							border-radius: 14rpx;
							background-color: white;
							color: #000;
							border: 2rpx solid rgba(187, 187, 187, 0.5294117647);
							padding: 0 20rpx;
							max-width: 600rpx;
							/* overflow: hidden; */
							white-space: nowrap;
							text-overflow: ellipsis;
							
							.left-message {
								white-space: pre-wrap;
								display: flex;
								flex-wrap: wrap;
								align-items: flex-start;
								text-overflow: ellipsis;
								height: auto;
								max-width: 50ch;
							}
						}
					}
					
					&+.li {
						margin: 20rpx auto 0;
					}
				}
			}
		}

		.fixed {
			position: fixed;
			left: 50%;
			bottom: 0;
			transform: translate(-50%, 0);
			width: 100%;
			height: 112rpx;
			background: #fff;
			display: flex;
			align-items: center;
			justify-content: space-between;
			
			image {
				width: 50rpx;
				height: 56rpx;
				margin: 0 14rpx 0 18rpx;
			}
			
			/deep/.is-input-border {
				border: none;
			}
			
			/deep/.uni-easyinput__content-input {
				width: 500rpx;
				height: 56rpx;
				line-height: 56rpx;
				border-radius: 28rpx;
				padding-left: 0 !important;
				padding-right: 0 !important;
			}
			
			/deep/.uni-input-input {
				background: #F1F3FA;
				text-align: left;
				text-indent: 32rpx;
				font-size: 18rpx;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #B3B3B3;
				border: none;
				box-shadow: none;
			}
			
			/deep/.uni-input-placeholder {
				z-index: 2;
				text-indent: 32rpx;
			}
			
			.voice {
				width: 500rpx;
				height: 56rpx;
				line-height: 56rpx;
				border-radius: 12rpx;
				background: #F1F3FA;
				text-align: center;
				font-size: 18rpx;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #B3B3B3;
			}
			
			.add {
				width: 50rpx;
				height: 50rpx;
			}
			
			.send {
				background-color: #5074fa;
				border: 0px solid #fff;
				width: 150rpx;
				border-radius: 100rpx;
				height: 56rpx;
				line-height: 56rpx;
				text-align: center;
				color: #fff;
				font-size: 18rpx;
				letter-spacing: 10rpx;
				text-indent: 10rpx;
			}
		}
	}
	.load-more{
		font-size: 16rpx;
		color: '#c6c6c6';
		text-align: center;
	}
	.message-icon{
		width: 30rpx;
		height: 30rpx; 
		margin-right: 10px;
	} 
	@-webkit-keyframes rotation {
		 from {
			 -webkit-transform: rotate(0deg);
		 }
		 to {
			 -webkit-transform: rotate(360deg);
		 }
	 }
	//兼容不同版本浏览器
	//3s 为转速 值越小 速度越快
	 .message-icon-loading {
		 -webkit-transform: rotate(360deg);
		 animation: rotation 3s linear infinite;
		 -moz-animation: rotation 3s linear infinite;
		 -webkit-animation: rotation 3s linear infinite;
		 -o-animation: rotation 3s linear infinite;
	 }
</style>